// pages/ai/creativeHall/index.js

const {
  aiCreationApi
} = require("../../../api/index");
const {
  ALIOSS
} = require("../../../api/config/config");
import {
  globalApi,
} from "../../../api/index";
// const {
//   uploadFile
// } = require('../../../utils/ossUploader')
import {
  uploadFile
} from "../../../utils/ossUploader";

const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgSuffix: "", //图片后缀
    navTop: app.globalData.navTop,
    navObj: app.globalData.navObj,
    navH: 0, //导航栏高度
    navH2: 0, //导航栏高度
    title: "",
    visible: false,
    visibleDegreeContro: false,
    firstNumber: 0, //风格弹窗高度差值
    ItemName: "", //选择的风格
    loadingShow: false, //随机风格按钮是否处于加载状态
    styleImageList: [],
    quantity: true, //选择生成图片张数
    isShowList: [], //是否有获取到风格
    allStyleData: {},
    sumIntegralValue: null, //总算力值
    oneIntegralValue: null, //单张出图算力值
    controller: [],
    //控制选择类型数据源
    controllerData: [{
        name: "室内",
        arr: [{
            label: "风格改造",
            value: "s3",
          },
          {
            label: "灵感创作",
            value: "s4",
          },
          {
            label: "灵感创作（线稿专属）",
            value: "s1",
          },
          {
            label: "风格改造（线稿专属）",
            value: "s2",
          },
          {
            label: "空间设计（毛坯专属）",
            value: "s5",
          },
        ],
      },
      {
        name: "建筑",
        arr: [{
            label: "风格改造",
            value: "j4",
          },
          {
            label: "灵感创作",
            value: "j1",
          },
          {
            label: "灵感创作（线稿专属）",
            value: "j3",
          },
          {
            label: "风格改造（线稿专属）",
            value: "j2",
          },
        ],
      },
      {
        name: "景观",
        arr: [{
            label: "风格改造",
            value: "g3",
          },
          {
            label: "灵感创作",
            value: "g2",
          },
          {
            label: "灵感创作（线稿专属）",
            value: "g1",
          },
        ],
      },
    ], //程度控制
    dimensionOfPicture: [{
        name: "16:9",
        code: 16,
        isIshow: false,
      },
      {
        name: "1:1",
        code: 1,
        isIshow: true,
      },
      {
        name: "3:4",
        code: 3,
        isIshow: false,
      },
    ], //图片尺寸
    currentCode: 1, //默认图片比例1:1
    pictureSizeOptions: false, //图片尺寸选中
    cityValue: [],
    degreeOptionName: "",
    degreeOptionCode: "",
    recordUpdatesIndex: null, //记录更新在第三级别更新后的二级下标
    selectedLevelLabel: "",
    oneName: "", //一级分类name
    styleLoadingShow: true, //风格加载状态
    lastClickTime: 0, // 初始化上次点击时间为0
    sharePosterStyleData: "", //分享海报用风格数据
    IsVipAuth: false, //风格否需要会员
    IsVip: false, //随机风格时是否为会员
    whetherToClearGraphData: false, //是否清除图生图数据
    /**
     * ai创作一键出图参数
     */
    styleTree: [],
    styleSecondarySubscript: 0, //风格一级下标
    secondLevelIndex: null, //风格的二级下标
    threeSecondLevelIndex: null, //更新三级分类
    selectPhotoPath: null,
    homePageAllParameter: {}, //智能创作页传递过来的所有参数
    goOnspacetype: null, //继续创作时需要用到的程度控制数据源类型
    Result: "", //描述
    imageNumber: 2, //生成图片张数,
    // sessionID: '', //会话id
    upUrlData: "", //上传图片地址
    paramsStyle: "", //风格id和name
    //增加确认按钮风格参数赋值
    notarize: "",
    uploadBackEndparamsStyle: {},
    createImgInfo: { //生图页面预览信息
      url: '',
      style: '',
      des: "",
      width: "",
      height: "",
      size: ""
    }
  },

  //跳转作品创建历史
  toWorkHistory() {
    let _this = this
    if (!wx.getStorageSync("token")) {
      wx.showModal({
        content: "查看生图历史记录需要登录，是否登录！",
        success(res) {
          if (res.confirm) {
            _this.authenticationLogin(true);
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
      return;
    }
    wx.navigateTo({
      url: "/pages/ai/creationHistory/index",
    });
  },
  /**
   * 登录验证
   */
  authenticationLogin(e) {
    console.log('e', e);
    // visible:true打开弹窗，false为关闭
    const popup = this.selectComponent("#popupid");
    popup.setData({
      visible: e || false,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let _this = this;
    //navigateTo接收参数
    const eventChannel = this.getOpenerEventChannel();
    eventChannel &&
      eventChannel.on &&
      eventChannel.on("aiAuthoringParameters", async function (data) {
        _this.setData({
          homePageAllParameter: data,
          title: data.createtitle,
          goOnspacetype: data.spacetype,
        });
        await _this.getExpendPowerValue(true)
        await _this.getAiStyleTree();
        await _this.pictureControlType();
      });

    //继续创作时重置空间名称和程度控制数据源
    if (options.createtitle) {
      _this.setData({
        title: options.createtitle,
        goOnspacetype: Number(options.spacetype),
        whetherToClearGraphData: true
      });
      _this.pictureControlType();
    }

    // 获取导航栏高度
    let systemInfo = wx.getSystemInfoSync();
    let popupHeight = systemInfo.statusBarHeight;
    this.setData({
      navH: systemInfo.statusBarHeight,
      navH2: popupHeight > 20 ? popupHeight : popupHeight - 12,
    });
    this.processingType();
    if (options?.type) {
      this.setData({
        upUrlData: wx.getStorageSync("shareImg"),
      });
      this.getExpendPowerValue(true)
      this.getAiStyleTree();
    }
  },
  onShow() {
    this.authenticationLogin();
  },

  /**
   * 创建会话id
   */
  // creatingASessionfun() {
  //   let _this = this
  //   aiCreationApi.creatingASession({}).then((res) => {
  //     _this.setData({
  //       sessionID: res.result
  //     })
  //   })
  // },

  /**
   * 处理手机类型-判断设备是否为刘海屏
   */
  processingType() {
    const {
      model,
      statusBarHeight
    } = wx.getSystemInfoSync();
    //根据安全高度判断 ；
    if (
      model.includes("iPhone 11") ||
      model.includes("iPhone 12") ||
      model.includes("iPhone 13") ||
      model.includes("iPhone14") ||
      (model.includes("iPhone") &&
        (model.includes("Pro") ||
          model.includes("mini") ||
          model.includes("X")) &&
        statusBarHeight > 20)
    ) {
      this.firstNumber = true;
    } else {
      this.firstNumber = false;
    }
    const excessHeight = this.firstNumber ? 160 : 88;
    this.setData({
      firstNumber: excessHeight,
    });
  },

  /**
   * 风格选项卡
   */
  handlePopup() {
    this.setData({
      visible: true,
    });
  },
  // 关闭风格选项卡
  closehandlePopup() {
    this.setData({
      visible: false,
    });
  },
  /**
   * 程度控制
   */
  degreeControl() {
    this.setData({
      visibleDegreeContro: true,
    });
  },

  // 滚动选择数据
  onColumnChange(e) {
    this.setData({
      degreeOptionCode: e.detail.value[0],
      degreeOptionName: e.detail.label[0],
      cityValue: e.detail.value,
    });
  },
  //关闭程度选项卡
  // closedegreeControl() {
  //   this.setData({
  //     visibleDegreeContro: true
  //   })
  // },

  //点击空白处关闭风格选项卡（浮层隐藏或显示时触发）
  onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible,
      visibleDegreeContro: false,
    });
  },
  // 获取风格列表
  getAiStyleTree() {
    let _this = this;
    const {
      spacetypeid
    } = this.data.homePageAllParameter;
    const findDrawingParameterKey = wx.getStorageSync("drawingParameter"); //继续创作时获取空间id和name
    aiCreationApi
      .getAiStyleTree({
        ID: spacetypeid || findDrawingParameterKey.spaceType.id || "",
      })
      .then((res) => {
        _this.setData({
          styleTree: res.Result,
          styleLoadingShow: false, //风格加载状态
        });
      });
  },

  //获取图片控制程度
  pictureControlType() {
    const {
      spacetype
    } = this.data.homePageAllParameter;

    if (spacetype != void 0 || this.data.goOnspacetype != void 0) {
      this.setData({
        controller: this.data.controllerData[spacetype || this.data.goOnspacetype].arr,
        degreeOptionName: this.data.controllerData[spacetype || this.data.goOnspacetype].arr[0]
          .label,
        degreeOptionCode: this.data.controllerData[spacetype || this.data.goOnspacetype].arr[0]
          .value,
      });
    }
  },

  // 获取用户每次消耗的算力值
  getExpendPowerValue(e) {
    aiCreationApi
      .getExpendIntegralApi({})
      .then((res) => {
        let user = wx.getStorageSync('userInfo') //获取当前用户等级
        const itemValue = res.Result.find(obj => obj.VipType === user.VIPWeight);
        this.setData({
          oneIntegralValue: itemValue.StyleGenerateImages,
        })
        if (e) {
          this.setData({
            sumIntegralValue: itemValue.StyleGenerateImages * 2
          })
        }
      });
  },

  //预览风格大图片
  PreviewPicture(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.atpresentimg, // 当前显示图片的http链接
      urls: e.currentTarget.dataset.imglist, // 需要预览的图片http链接列表
    });
  },
  // 切换一级分类
  screen(e) {
    const index = e.currentTarget.dataset.bindex;
    let oneName = e.currentTarget.dataset.onename.ItemName;
    let IsVipAuth = e.currentTarget.dataset.IsVipAuth;
    this.setData({
      styleSecondarySubscript: index, // 更新当前选中项的索引
      oneName: oneName,
      secondLevelIndex: null,
      IsVipAuth: IsVipAuth,
    });
  },
  //二级选择分类
  secondarySortSelection(e) {
    let ItemName = e.currentTarget.dataset.items.ItemName;
    const index = e.currentTarget.dataset.index;
    let isshowThree =
      e.currentTarget.dataset.items.children[index].children.length;
    let twoName =
      isshowThree === 0 ?
      `${ItemName}/${e.currentTarget.dataset.items.children[index].ItemName}` :
      "";

    let styleImageList =
      e.currentTarget.dataset.items.children[index].StyleImageList;
    let paramsStyle =
      isshowThree === 0 ? e.currentTarget.dataset.items.children[index] : "";
    let isShowList = e.currentTarget.dataset.items.children;
    let IsVipAuth = e.currentTarget.dataset.items.children[index].IsVipAuth;
    // wx.setStorageSync('styleStr', `${e.currentTarget.dataset.items.ItemName}-${e.currentTarget.dataset.items.children[index].ItemName}`)
    this.setData({
      allStyleData: e.currentTarget.dataset.items,
      ItemName: twoName,
      secondLevelIndex: index, // 更新当前选中项的索引
      styleImageList: styleImageList, //风格模版图片
      paramsStyle: paramsStyle,
      isShowList: isShowList, //是否获取到了风格
      recordLevelDirectory: this.data.styleSecondarySubscript, //记录一级目录下标
      selectedLevelLabel: `${e.currentTarget.dataset.items.ItemName}-${e.currentTarget.dataset.items.children[index].ItemName}`,
      threeSecondLevelIndex: null,
      loadingShow: false, //关闭随机风格的loading
      IsVipAuth: IsVipAuth,
    });
  },
  //三级分类
  threeSecondarySortSelection(e) {
    let VALUE = e.currentTarget.dataset
    let threeIndex = VALUE.threeindex;
    let twoItemName = VALUE.items.ItemName; //二级名称
    let threeItemName =
      VALUE.items.children[threeIndex].ItemName; //三级名称
    let styleImageList =
      VALUE.items.children[threeIndex].StyleImageList; //三级图册
    let paramsStyle = VALUE.items.children[threeIndex];
    let IsVipAuth =
      VALUE.items.children[threeIndex].IsVipAuth;

    // wx.setStorageSync('styleStr', `${twoItemName}-${threeItemName}`)
    this.setData({
      ItemName: `${this.data.oneName}/${twoItemName}/${threeItemName}`,
      styleImageList: styleImageList, //风格模版图片
      threeSecondLevelIndex: threeIndex, // 更新三级分类选中项的索引
      recordUpdatesIndex: this.data.secondLevelIndex,
      selectedLevelLabel: `${twoItemName}-${threeItemName}`,
      paramsStyle: paramsStyle,
      loadingShow: false, //关闭随机风格的loading
      IsVipAuth: IsVipAuth,
    });
  },

  //重置风格
  // resetStyleData() {
  //   wx.setStorageSync('styleStr', "")
  //   this.setData({
  //     styleImageList: [],
  //     styleSecondarySubscript: 0,
  //     secondLevelIndex: null,
  //     recordUpdatesIndex: null,
  //     threeSecondLevelIndex: null,
  //     ItemName: '',
  //     paramsStyle: {},
  //     selectedLevelLabel: ''
  //   })
  // },

  //随机风格
  randomaiStyle() {
    let _this = this;
    const {
      spacetypeid
    } = _this.data.homePageAllParameter;

    //当前随机看看是否登录或者是否是会员
    const VIPWeight = wx.getStorageSync("userInfo").VIPWeight;
    this.setData({
      IsVip: VIPWeight > 1 ? true : false
    })

    //节流操作
    const now = Date.now(); // 获取当前时间（毫秒）
    if (now - _this.data.lastClickTime < 800) {
      return;
    }
    this.setData({
      lastClickTime: now, // 更新上次点击时间
      loadingShow: true,
    });

    const findDrawingParameterKey = wx.getStorageSync("drawingParameter"); //继续创作时获取空间id和name
    aiCreationApi
      .getRandomaiStyle({
        ID: spacetypeid || findDrawingParameterKey.spaceType.id,
        IsVip: this.data.IsVip
      })
      .then((res) => {
        if (res.StatusCode === 200) {
          let ImageList = res.Result.StyleImageList;
          _this.setData({
            loadingShow: false,
            paramsStyle: res.Result,
            styleImageList: ImageList,
            ItemName: res.Result.ItemName,
            secondLevelIndex: null,
            selectedLevelLabel: res.Result.ItemName,
            styleSecondarySubscript: 0,
          });
          wx.showToast({
            title: `风格为：${res.Result.ItemName}`,
            icon: "none",
            duration: 2000,
          });
        } else {
          wx.showModal({
            title: "",
            cancelText: "好的",
            confirmText: "复制",
            content: '该空间风格属性需要会员才能使用，请修改非会员风格选项或复制链接去官网、APP充值会员！',
            success(res) {
              if (res.confirm) {
                wx.setClipboardData({
                  data: "https://api.aiiiin.com/app/release/downloadandroidapp",
                  success(res) {
                    wx.showToast({
                      title: "复制成功",
                      icon: "none",
                    });
                  },
                });
              } else if (res.cancel) {
                console.log("用户点击取消");
              }
            },
          });
          _this.setData({
            loadingShow: false,
          });
        }
      })
      .catch((res) => {
        wx.showToast({
          title: `获取失败${res.Message}`,
          icon: "none",
          duration: 2000,
        });
        _this.setData({
          loadingShow: false,
        });
      });
  },
  //确定风格数据
  ConfirmStyle() {
    if (this.data.paramsStyle) {
      this.setData({
        notarize: this.data.ItemName, //前端显示用
        uploadBackEndparamsStyle: this.data.paramsStyle, //后端用风格name和id
        loadingShow: false, //关闭当前随机风格loading
        sharePosterStyleData: this.data.selectedLevelLabel,
      });
      wx.setStorageSync("styleStr", this.data.sharePosterStyleData); //给生图完成后分享海报
      this.closehandlePopup();
    } else {
      wx.showToast({
        title: "请选择风格",
        icon: "none",
        duration: 2000,
      });
    }
  },

  /**
   *  填写描述画面
   */
  generateRandomDescription() {
    const {
      spacetypeid
    } = this.data.homePageAllParameter;
    const drawingParameter = wx.getStorageSync("drawingParameter");
    let _this = this;
    aiCreationApi
      .getrandomfeaturedWords({
        ID: spacetypeid || drawingParameter.spaceType?.id,
        IsPositive: true,
      })
      .then((res) => {
        _this.setData({
          Result: res.Result,
        });
      });
  },
  //监听描述词
  handleInput(e) {
    this.setData({
      Result: e.detail.value, // 当用户输入时，更新 textarea 的值
    });
  },
  /**
   * 图片尺寸
   */
  selectPictureSize(value) {
    let {
      code
    } = value.currentTarget.dataset.sizeitem;
    this.setData({
      currentCode: code, // 更新当前显示的 code
    });

    let newDimension = this.data.dimensionOfPicture.map((item) => {
      return {
        ...item,
        isIshow: item.code === code ? true : false,
      };
    });

    this.setData({
      dimensionOfPicture: newDimension,
    });
  },

  /**
   *生成图片张数
   */
  generate(e) {
    let _this = this
    let {
      imgnumber
    } = e.currentTarget.dataset
    if (!wx.getStorageSync("token")) {
      wx.showModal({
        content: "当前没有用户没有登录，是否登录!",
        success(res) {
          if (res.confirm) {
            _this.authenticationLogin(true);
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
      return;
    } else {
      const VIPWeight = wx.getStorageSync("userInfo").VIPWeight;
      if (VIPWeight > 1 || imgnumber === 2) {
        // 判断当前是否点击的是否是自身选项
        if (imgnumber === this.data.imageNumber) {
          return
        }

        let currentQuantity = this.data.quantity;
        const newQuantity = !currentQuantity;
        this.getExpendPowerValue()

        this.setData({
          imageNumber: imgnumber,
          quantity: newQuantity,
          sumIntegralValue: this.data.oneIntegralValue * imgnumber,
        });
      } else {
        wx.showModal({
          title: "",
          cancelText: "取消",
          confirmText: "复制",
          content: "当前图片张数含会员服务选项，需要生成更多图片张数请复制链接去官网、APP充值会员！",
          success(res) {
            if (res.confirm) {
              wx.setClipboardData({
                data: "https://api.aiiiin.com/app/release/downloadandroidapp",
                success(res) {
                  wx.showToast({
                    title: "复制成功",
                    icon: "none",
                  });
                },
              });
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      }
    }
  },
  //
  generateRandomString(length) {
    // const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    // let result = '';
    // const charLength = chars.length;
    // for (let i = 0; i < length; i++) {
    //   result += chars.charAt(Math.floor(Math.random() * charLength));
    // }
    // return result;
    // 第二种方案
    return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
      var r = (Math.random() * 16) | 0,
        v = c === "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  },
  /**
   * 拍摄或从手机相册中选择图片图生图
   */
  upimages() {
    let _this = this;
    wx.chooseMedia({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
      camera: "back",
      success(res) {
        _this.setData({
          imgSuffix: res.tempFiles[0].tempFilePath
        })
        wx.getImageInfo({
          src: res?.tempFiles[0].tempFilePath,
          success: res => {
            const width = res.width; // 图片宽度
            const height = res.height; // 图片高度
            if (width < height / 3) {
              wx.showToast({
                title: `请上传宽比高小于1:3的图片`,
                icon: "none",
                duration: 2000,
              });
              return
            }
            if (width <= 2800 && height <= 2800) {
              _this.setData({
                createImgInfo: {
                  ..._this.data.createImgInfo,
                  ...{
                    width: res.width,
                    height: res.height
                  }
                }
              })

              // let now = new Date();
              // const year = now.getFullYear();
              // const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以需要+1，并使用padStart补全为两位数
              // const day = String(now.getDate()).padStart(2, '0'); // 使用padStart补全为两位数
              // let uploadTime = `${year}-${month}-${day}`
              wx.showLoading({
                title: "上传中...",
              });
              let uploadFileName =
                _this.generateRandomString(45) +
                "." +
                _this.data.imgSuffix.split(".")[1];
              // let uploadFileName = _this.generateRandomString(16) + res.tempFiles[0].tempFilePath.split('tmp/')[1]
              uploadFile({
                  host: `${ALIOSS}`,
                  key: `temp/${uploadFileName}`,
                  filePath: _this.data.imgSuffix,
                })
                .then((res) => {
                  if (res.statusCode == 204) {
                    // const selectPhotoPath = `${ALIOSS}/ai/generateimages/${uploadTime}/${uploadFileName}`
                    const photoPath = `temp/${uploadFileName}`; //图片上传oss的地址
                    //上传oss地址处理图片
                    aiCreationApi
                      .ossOperationPicture({
                        url: photoPath,
                        thumb: {
                          mode: 0,
                          size: {
                            width: 0,
                            height: 0,
                          },
                        },
                        format: "",
                        targetPath: "ai/generateimages",
                      })
                      .then((res) => {
                        const selectPhotoPath = `${ALIOSS}/${res.url}`; //oss处理后得新地址
                        _this.setData({
                          selectPhotoPath: selectPhotoPath,
                          upUrlData: selectPhotoPath,
                        });
                        wx.hideLoading();
                      })
                      .catch((error) => {
                        wx.showToast({
                          title: `上传失败:${error.statusCode}`,
                          icon: "none",
                          duration: 2000,
                        });
                        wx.hideLoading();
                      });
                  }
                })
                .catch((err) => {
                  wx.showToast({
                    title: `上传失败:${err}`,
                    icon: "none",
                    duration: 2000,
                  });
                  wx.hideLoading();
                });
            } else {
              wx.showToast({
                title: `请上传分辨率小于2800*2800的图片`,
                icon: "none",
                duration: 2000,
              });
            }
          }
        })

      },
      fail(err) {
        console.error("选择媒体失败", err);
      },
    });
  },

  //移除选择图片
  deleteSelectPicture() {
    if (this.data.whetherToClearGraphData) {
      wx.removeStorageSync('shareImg')
    }
    this.setData({
      upUrlData: null,
    });
  },

  /**
   * 一键出图
   */
  async mapMaking(e) {
    let _this = this;
    if (!wx.getStorageSync("token")) {
      wx.showModal({
        content: "是否登录以使用算力值出图？",
        success(res) {
          if (res.confirm) {
            _this.authenticationLogin(true);
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
      return;
    } else {
      //判断当前是否有生图权限
      let limitsOfAuthorityCode = 'CreativeWork.BatchGenerateImages'
      let useRes = await globalApi.getUserinfoForToken({
        ActivePort: 3
      })
      let isPermission = useRes.Result.Permissions.includes(limitsOfAuthorityCode)
      if (isPermission) {
        let {
          Telepathy
        } = useRes.Result

        if (Telepathy < this.data.sumIntegralValue) {
          // 检测算力值是否足够出图
          wx.showToast({
            title: '使用功能所需算力值不足，请充值算力值',
            icon: "none",
            duration: 2000,
          });
          return
        }

        const res = await aiCreationApi.getusergeneratestatusasync()
        if (res.BusinessCode) {
          const popup = this.selectComponent('#disablePanel');
          popup?.handlePopup(res.BusinessCode)
          return
        }
        //获取会话ID
        const dialogueRes = await aiCreationApi
          .creatingASession({})
          .then((res) => {
            return res;
          });

        const {
          spacetypeid,
          uploadname,
          skytype
        } =
        _this.data.homePageAllParameter;

        const {
          ItemName,
          ID
        } = _this.data.uploadBackEndparamsStyle;

        //一键出图参数
        let CreatePictureParameters = {
          msgId: dialogueRes.result, //会话id
          size: _this.data.currentCode, //图片尺寸
          num: _this.data.imageNumber, //图片数量
          // showImg: _this.data.upBase64Data, //上传的图片
          showImg: _this.data.upUrlData, //上传的图片
          style: {
            id: ID || "",
            itemName: ItemName || "",
          }, //风格参数
          spaceType: {
            id: spacetypeid,
            itemName: uploadname,
          }, //空间名称
          type: skytype,
          highDefinition: false,
          // controller: "",
          bannerType: 1,
          forwardDescribe: _this.data.Result,
          clienType: 5,
          controller: _this.data.degreeOptionCode,
        };

        const inputValue = this.data.Result.trim(); // 获取并去除前后空格的值
        const regex = /\S+/; // 正则表达式，匹配至少一个非空白字符

        if (regex.test(inputValue) && CreatePictureParameters.style.itemName) {
          try {
            //检查是否为继续创作
            const storageInfo = wx.getStorageInfoSync();
            if (storageInfo.keys.includes("drawingParameter")) {
              const drawingParameter = wx.getStorageSync("drawingParameter");
              let {
                spaceType,
                type
              } = drawingParameter;
              CreatePictureParameters.spaceType = spaceType; //重新赋值空间id和name
              CreatePictureParameters.type = type; //重新赋值空间类型
            }

            wx.setStorageSync("drawingParameter", CreatePictureParameters);
            _this.setData({
              createImgInfo: {
                ..._this.data.createImgInfo,
                ...{
                  url: _this.data.upUrlData,
                  style: _this.data.ItemName,
                  des: _this.data.Result,
                  size: _this.data.currentCode
                }
              }
            })
            wx.setStorageSync('createImgInfo', _this.data.createImgInfo)
            const {
              spacetype,
              createtitle
            } = this.data.homePageAllParameter; //将空间name和程度控制数据源类型传递给下一个页面

            // 判断是否拥有会员权限（VIPWeight大于1小于等于4都是会员）
            const VIPWeight = wx.getStorageSync("userInfo").VIPWeight;

            if (VIPWeight <= 1 && this.data.IsVipAuth) {
              // wx.showModal({
              //   title: "",
              //   cancelText: "好的",
              //   confirmText: "复制",
              //   content: "生图功能含会员服务选项，请修改为非会员风格选项或复制链接去官网、APP充值会员！",
              //   success(res) {
              //     if (res.confirm) {
              //       wx.setClipboardData({
              //         data: "https://api.aiiiin.com/app/release/downloadandroidapp",
              //         success(res) {
              //           wx.showToast({
              //             title: "复制成功",
              //             icon: "none",
              //           });
              //         },
              //       });
              //     } else if (res.cancel) {
              //       console.log("用户点击取消");
              //     }
              //   },
              // });
              return;
            }

            if (dialogueRes.statusCode == 200) {
              wx.navigateTo({
                url: `/pages/ai/imgCreation/index?createtitle=${
                  createtitle || this.data.title
                }&spacetype=${spacetype || this.data.goOnspacetype}`,
              });
            } else {
              wx.showToast({
                title: "获取会话ID失败！",
                icon: "error",
                duration: 2000,
              });
            }
          } catch (e) {
            console.error("存入本地存储失败", e);
          }
        } else {
          wx.showToast({
            title: CreatePictureParameters.style.itemName ?
              "请填写描述画面" : "请选择风格",
            icon: "none",
            duration: 2000,
          });
        }
      } else {
        wx.showToast({
          title: '当前你没有权限使用生图功能,请联系管理员',
          icon: "none",
          duration: 2000,
        });
      }
    }
  },
});